<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用Proxy实现观察者模式</title>
</head>
<body>
    <h1>实例：使用Proxy实现观察者模式</h1>

    <script>
        // 定义观察者类
        const queuedObservers = new Set();

        const observe = fn => queuedObservers.add(fn);
        const observable = obj => new Proxy(obj, {set});

        function set(target, key, value, receiver) {
            const result = Reflect.set(target, key, value, receiver);
            queuedObservers.forEach(observer => observer());
            return result;
        }

        // 使用示例
        const person = observable({
            name: '张三',
            age: 20
        });

        function print() {
            console.log(`${person.name}, ${person.age}`);
        }

        observe(print);
        person.name = '李四'; // 输出：李四, 20

        // 另一个观察者示例
        const user = observable({
            name: '王五',
            address: {
                city: '北京'
            }
        });

        const updateDOM = () => {
            console.log('DOM已更新:', user.name, user.address.city);
        };

        observe(updateDOM);
        user.name = '赵六'; // 输出：DOM已更新: 赵六 北京
    </script>
</body>
</html> 